<template>
  <span>{{innerValue}}</span>
</template>

<script>
import { initDictOptions, filterDictText } from '@/components/dict/ZDictSelectUtil'
export default {
  props: {
    value: [String, Number],
    params: Object,
    renderOptions: Object,
    cellProps: Object
  },
  data() {
    return {
      innerValue: '',
      options: []
    }
  },
  watch: {
    value: {
      handler() {
        this.getInnerValue()
      }
    }
  },
  methods: {
    getInnerValue() {
      this.innerValue = this.value ? filterDictText(this.options, this.value) : ''
    },
    initDictData() {
      const { column } = this.params
      if (column.own && column.own.loading) {
        return column.own.loading
      }
      if (column.own && column.own.options) {
        return new Promise((resolve, reject) => {
          resolve({ ...column.own.options })
        })
      }
      const loading = new Promise((resolve, reject) => {
        // 根据字典Code, 初始化字典数组
        initDictOptions(this.cellProps.dictCode).then(res => {
          if (res.success && res.result) {
            this.$set(column, 'own', { // 把options放到column上避免每行都请求数据
              options: res.result,
              loading: false
            })
            resolve(res.result)
          }
        })
      })
      this.$set(column, 'own', { loading: loading })
      return loading
    },
    init() {
      this.initDictData().then(res => {
        this.options = []
        res.items.forEach(item => {
          this.options.push({
            label: item.itemText,
            value: item.itemValue
          })
        })
        this.getInnerValue()
      })
    }
  },
  created() {
    this.init()
  }
}
</script>
